package org.jadelyre.core;

import org.jadelyre.utils.ByteBufferUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class ReadCompletionHandler implements CompletionHandler<Integer, Channel> {

    private static final Logger logger = LoggerFactory.getLogger(ReadCompletionHandler.class);

    private AsynchronousSocketChannel asynchronousSocketChannel;
    private ByteBuffer readByteBuffer;
    public ReadCompletionHandler(AsynchronousSocketChannel asynchronousSocketChannel,ByteBuffer readByteBuffer){
        this.asynchronousSocketChannel = asynchronousSocketChannel;
        this.readByteBuffer = readByteBuffer;
    }
    @Override
    public void completed(Integer result, Channel channel) {
        if (result > 0){
            //读取到数据
            readByteBuffer.flip();
            ByteBuffer newByteBuffer = ByteBufferUtils.copy(readByteBuffer);
            channel.getDecodeWorker().work(newByteBuffer);
            readByteBuffer.clear();
            asynchronousSocketChannel.read(readByteBuffer, channel, this);
        }else {
            if (channel.getJadeLyre().isStarted()) {
                channel.close();
            }
        }
    }

    @Override
    public void failed(Throwable exc, Channel channel) {
        if (logger.isDebugEnabled()) {
            NodeAddress remoteNodeAddress = channel.getRemoteNodeAddress();
            logger.debug("读取host为：{}的数据失败，可能连接关闭", remoteNodeAddress.getIp() + ":" + remoteNodeAddress.getPort());
        }
        if (channel.getJadeLyre().isStarted()) {
            channel.close();
        }
    }

    public ByteBuffer getReadByteBuffer() {
        return readByteBuffer;
    }
}
